// app/users/page.tsx (assuming Next.js structure, but can be adapted to other React setups)
"use client"
import { useState } from 'react';
import { useForm } from 'react-hook-form';
import {
  Table,
  TableBody,
  TableCell,
  TableHead,
  TableHeader,
  TableRow,
} from '@/components/ui/table';
import { Button } from '@/components/ui/button';
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
} from '@/components/ui/dialog';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { z } from 'zod';
import { zodResolver } from '@hookform/resolvers/zod';
import {User} from '@/types/User'
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select';
import {
  Pagination,
  PaginationContent,
  PaginationItem,
  PaginationLink,
  PaginationNext,
  PaginationPrevious,
} from '@/components/ui/pagination';
import { Pencil, Trash2, Plus } from 'lucide-react';
import api from "@/config/http";
import {toast} from "sonner"; // Assuming lucide-react for icons

import {CreateUserForm} from '@/components/user/CreateUserForm'

export default function UserManagementPage() {
  const [users, setUsers] = useState<User[]>([
    {
      id: '1',
      name: 'John Doe',
      address: '123 Main St, City A',
      phone: '123-456-7890',
      gender: 'Male',
      birthDate: '1990-01-01',
      weChat: 'johnwx123',
      role: '4',
    },

    // Add more dummy users for pagination testing

    // ... (you can add more as needed)
  ]);
  const [isDialogOpen, setIsDialogOpen] = useState(false);
  const [currentUser, setCurrentUser] = useState<User | null>(null);
  const [formData, setFormData] = useState({
    name: '',
    address: '',
    phone: '',
    gender: '',
    birthDate: '',
    weChat: '',
    role: '2',
  });

  const pageSize = 10;
  const [currentPage, setCurrentPage] = useState(1);
  const itemsPerPage = 5; // Adjust as needed


  const handleOpenDialog = (user?: User) => {
    if (user) {
      setCurrentUser(user);
      setFormData({
        name: user.name,
        address: user.address,
        phone: user.phone,
        gender: user.gender,
        birthDate: user.birthDate,
        weChat: user.weChat,
        role: user.role,
      });
    } else {
      setCurrentUser(null);
      setFormData({
        name: '',
        address: '',
        phone: '',
        gender: '',
        birthDate: '',
        weChat: '',
        role: '2',
      });
    }
    setIsDialogOpen(true);
  };

  const handleCloseDialog = () => {
    setIsDialogOpen(false);
    setCurrentUser(null);
  };

  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const { name, value } = e.target;
    setFormData((prev) => ({ ...prev, [name]: value }));
  };

  const handleGenderChange = (value: string) => {
    setFormData((prev) => ({ ...prev, gender: value }));
  };

  const handleRoleChange = (value: string) => {
    setFormData((prev) => ({ ...prev, role: value }));
  };


  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    if (currentUser) {
      // Update user
      setUsers((prev) =>
          prev.map((u) =>
              u.id === currentUser.id ? { ...u, ...formData } : u
          )
      );
    } else {
      // Add new user
      const newUser: User = {
        id: Date.now().toString(),
        ...formData,
      };
      api.post("/usr",newUser)
          .then((data:any)=>{
            if (data.status==200){
              toast("添加用户成功")
            }
          })
      setUsers((prev) => [...prev, newUser]);
    }
    handleCloseDialog();
    setCurrentPage(1); // Reset to first page after add/edit
  };

  const handleDelete = (user: User) => {
    if (confirm('你确定要删除该用户么？')) {
      setUsers((prev) => prev.filter((u) => u.id !== user.id));
      setCurrentPage(1); // Reset to first page after delete
    }
  };

  const handleSuccess = () => {
    setIsDialogOpen(false);
    fetchUsers(currentPage);
  };

  const fetchUsers = async (page: number) => {
    try {
      const response = await api.get(`/api/users?page=${page}&pageSize=${pageSize}`);
      setUsers(response.data.users);
      // setTotalPages(response.data.totalPages || 1);1
    } catch (error) {
      console.error("获取用户列表失败:", error);
      alert("获取用户列表失败，请稍后重试");
    }
  };

  const indexOfLast = currentPage * itemsPerPage;
  const indexOfFirst = indexOfLast - itemsPerPage;
  const currentUsers = users.slice(indexOfFirst, indexOfLast);
  const totalPages = Math.ceil(users.length / itemsPerPage);

  return (
      <div className="p-4">
        <div className="flex justify-between items-center mb-4">
          <h1 className="text-2xl font-bold">用户管理</h1>
          <Button onClick={() => handleOpenDialog()}>
            <Plus className="mr-2 h-4 w-4" /> 添加用户
          </Button>
        </div>

        <Table>
          <TableHeader>
            <TableRow>
              <TableHead>姓名</TableHead>
              <TableHead>角色</TableHead>
              <TableHead>地址</TableHead>
              <TableHead>电话</TableHead>
              <TableHead>性别</TableHead>
              <TableHead>出生年月</TableHead>
              <TableHead>微信号</TableHead>
              <TableHead>操作</TableHead>
            </TableRow>
          </TableHeader>
          <TableBody>
            {currentUsers.map((user) => (
                <TableRow key={user.id}>
                  <TableCell>{user.name}</TableCell>
                  <TableCell>{user.role}</TableCell>
                  <TableCell>{user.address}</TableCell>
                  <TableCell>{user.phone}</TableCell>
                  <TableCell>{user.gender}</TableCell>
                  <TableCell>{user.birthDate}</TableCell>
                  <TableCell>{user.weChat}</TableCell>
                  <TableCell className="flex space-x-2">
                    <Button variant="ghost" size="icon" onClick={() => handleOpenDialog(user)}>
                      <Pencil className="h-4 w-4" />
                    </Button>
                    <Button variant="ghost" size="icon" onClick={() => handleDelete(user)}>
                      <Trash2 className="h-4 w-4" />
                    </Button>
                  </TableCell>
                </TableRow>
            ))}
          </TableBody>
        </Table>

        <div className="mt-4">
          <Pagination>
            <PaginationContent>
              <PaginationItem>
                <PaginationPrevious
                    href="#"
                    onClick={(e) => {
                      e.preventDefault();
                      setCurrentPage((prev) => Math.max(prev - 1, 1));
                    }}
                />
              </PaginationItem>
              {Array.from({ length: totalPages }, (_, i) => i + 1).map((page) => (
                  <PaginationItem key={page}>
                    <PaginationLink
                        href="#"
                        isActive={page === currentPage}
                        onClick={(e) => {
                          e.preventDefault();
                          setCurrentPage(page);
                        }}
                    >
                      {page}
                    </PaginationLink>
                  </PaginationItem>
              ))}
              <PaginationItem>
                <PaginationNext
                    href="#"
                    onClick={(e) => {
                      e.preventDefault();
                      setCurrentPage((prev) => Math.min(prev + 1, totalPages));
                    }}
                />
              </PaginationItem>
            </PaginationContent>
          </Pagination>
        </div>

        <Dialog open={isDialogOpen} onOpenChange={setIsDialogOpen}>
          <DialogContent>
            <DialogHeader>
              <DialogTitle>{currentUser ? '编辑用户' : '添加新用户'}</DialogTitle>
            </DialogHeader>
            <CreateUserForm
                onSuccess={handleSuccess}
                onCancel={() => setIsDialogOpen(false)}
                user={currentUser}
            />

          </DialogContent>
        </Dialog>
      </div>
  );
}